package com.sky.service.impl;

import com.github.pagehelper.Page;
import com.sky.dto.OrdersPageQueryDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMannerMapper;
import com.sky.mapper.UserLoginMapper;
import com.sky.mapper.orderMapper;
import com.sky.service.StatisticsService;
import com.sky.vo.*;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.BigInteger;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

@Service
public class StatisticsServiceImpl implements StatisticsService {
    private static final Logger log = LoggerFactory.getLogger(StatisticsServiceImpl.class);
    @Autowired
    private orderMapper orderMapper;
    @Autowired
    private OrderMannerServiceImpI orderMannerServiceImpI;

    @Autowired
    private OrderMannerMapper orderMannerMapper;

    @Autowired
    private UserLoginMapper userLoginMapper;

    @Override
    public TurnoverReportVO ordersStatistics(String begin, String end) {
        // 使用正确的 DateTimeFormatter 格式
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

        // 解析字符串为 LocalDate
        LocalDate Begin = LocalDate.parse(begin, formatter);
        LocalDate End = LocalDate.parse(end, formatter);

        StringJoiner data = new StringJoiner(",");
        StringJoiner money = new StringJoiner(",");
        // 遍历日期范围
        LocalDate currentDate = Begin;
        LocalDate endDate = End;
        while (!currentDate.isAfter(endDate)) {
            // 获取当前日期的营业额
            double revenueForDate = getRevenueForDate(currentDate);
            data.add(currentDate.toString());
            money.add(String.valueOf(revenueForDate));
            // 移动到下一天
            currentDate = currentDate.plusDays(1);
        }
        return TurnoverReportVO.builder().dateList(data.toString()).turnoverList(money.toString()).build();
        //orderMapper.getordersStatistics(dataOverViewQueryDTO);
    }

    /**
     * 新增用户，总用户，日期
     * @param begin
     * @param end
     * @return
     */
    @Override
    public UserReportVO userStatis(LocalDate begin, LocalDate end) {
        List<LocalDate> datalist=new ArrayList<LocalDate>();
        List<Integer> user=new ArrayList<>();
        List<Integer> newUser=new ArrayList<>();
        while (!begin.isAfter(end)) {
            datalist.add(begin);
            begin = begin.plusDays(1);
        }
        //添加日期
        String join2 = StringUtils.join(datalist, ",");
        //查询每日用户数量
        for (LocalDate localDate : datalist) {
            OrdersPageQueryDTO ordersPageQueryDTO = new OrdersPageQueryDTO();
            ordersPageQueryDTO.setBeginTime(localDate.atStartOfDay());
            ordersPageQueryDTO.setEndTime(localDate.atTime(23, 59, 59));
            ordersPageQueryDTO.setStatus(Orders.COMPLETED);  // 假设状态为5代表订单已完成
            Page<OrderVO> pageResult = orderMannerMapper.serch(ordersPageQueryDTO);
            List<OrderVO> result = pageResult.getResult();
            Set<Long> collect = result.stream().map(s -> s.getUserId()).collect(Collectors.toSet());
            user.add(collect.size());
            int i = userLoginMapper.addUserCount(ordersPageQueryDTO.getBeginTime(), ordersPageQueryDTO.getEndTime());
            newUser.add(i);
        }
        String join = StringUtils.join(user, ",");
        String join1 = StringUtils.join(newUser, ",");

        return   UserReportVO.builder().newUserList(join1).totalUserList(join).dateList(join2).build();
    }

    @Override
    public OrderReportVO ordersStatis(LocalDate begin, LocalDate end) {
        //记录日期
        StringJoiner data = new StringJoiner(",");
        StringJoiner orderCountList = new StringJoiner(",");
        StringJoiner validOrderCountList=new StringJoiner(",");
        LocalDate currentDate = begin;
        OrdersPageQueryDTO ordersPageQueryDTO = new OrdersPageQueryDTO();
        //每日订单
        while (!currentDate.isAfter(end)) {
            data.add(currentDate.toString());
            //有效订单
            ordersPageQueryDTO.setBeginTime(currentDate.atStartOfDay());
            ordersPageQueryDTO.setEndTime(currentDate.atTime(23, 59, 59));
            ordersPageQueryDTO.setStatus(Orders.COMPLETED);  // 假设状态为5代表订单已完成
            Page<OrderVO> pageResult = orderMannerMapper.serch(ordersPageQueryDTO);
            List<OrderVO> result = pageResult.getResult();
            validOrderCountList.add(String.valueOf(result.size()));
            //总订单
            ordersPageQueryDTO.setStatus(null);  //所有状态订单
            Page<OrderVO> pageResult1 = orderMannerMapper.serch(ordersPageQueryDTO);
            List<OrderVO> result1 = pageResult1.getResult();
            orderCountList.add(String.valueOf(result1.size()));

            currentDate = currentDate.plusDays(1);
        }
        //周期有效订单总数
        ordersPageQueryDTO.setStatus(Orders.COMPLETED);
        ordersPageQueryDTO.setBeginTime(begin.atStartOfDay());
        ordersPageQueryDTO.setEndTime(end.atTime(23, 59, 59));
        Page<OrderVO> serch = orderMannerMapper.serch(ordersPageQueryDTO);
        int vail=serch.getResult().size();
        ordersPageQueryDTO.setStatus(null);
        Page<OrderVO> serch1 = orderMannerMapper.serch(ordersPageQueryDTO);
        int count=serch1.getResult().size();
        count=count==0?1:count;
        double orderCompletionRate=1.0*vail/count;
        return OrderReportVO.builder().dateList(data.toString()).orderCountList(orderCountList.toString()).
                orderCompletionRate(orderCompletionRate).validOrderCount(Integer.valueOf(vail))
                .totalOrderCount(Integer.valueOf(count)).validOrderCountList(validOrderCountList.toString()).build();
    }

    @Override
    public SalesTop10ReportVO selectTop10(LocalDate begin, LocalDate end) {
        OrdersPageQueryDTO ordersPageQueryDTO = new OrdersPageQueryDTO();
        ordersPageQueryDTO.setBeginTime(begin.atStartOfDay());
        ordersPageQueryDTO.setEndTime(end.atTime(23, 59, 59));
        ordersPageQueryDTO.setStatus(Orders.COMPLETED);
        Page<OrderVO> pageResult = orderMannerMapper.serch(ordersPageQueryDTO);
        List<OrderVO> result = pageResult.getResult();
        //收集这段日期中的所有订单号
        Set<BigInteger> collect = result.stream().map(Orders::getNumber).map(s->BigInteger.valueOf(Long.valueOf(s))).collect(Collectors.toSet());
        //将订单号对比订单详情表，来将菜品排序，生成的集合，每个元素是一个map集合，map集和只有一个键值对
        List<Map<String, Object>> maps = orderMapper.selectTop10(collect);
        String join2=StringUtils.join(maps.stream().map(s->s.get("count")).collect(Collectors.toList()),",");
        String join = StringUtils.join(maps.stream().map(s -> s.get("name")).collect(Collectors.toList()), ",");
        log.info("名称{} 数量{}",join,join2);
        return SalesTop10ReportVO.builder().nameList(join).numberList(join2).build();
    }

    public double getRevenueForDate(LocalDate date) {
        // 根据日期查询营业额，假设你已经有相应的查询方法
        // 在此可以根据业务逻辑查询并返回该日期的营业额
        OrdersPageQueryDTO ordersPageQueryDTO = new OrdersPageQueryDTO();
        ordersPageQueryDTO.setBeginTime(date.atStartOfDay());
        ordersPageQueryDTO.setEndTime(date.atTime(23, 59, 59));
        ordersPageQueryDTO.setStatus(Orders.COMPLETED);  // 假设状态为5代表订单已完成
        Page<OrderVO> pageResult = orderMannerMapper.serch(ordersPageQueryDTO);

        // 计算并返回当天的营业额
        List<OrderVO> orders = pageResult.getResult();
        BigDecimal sum=new BigDecimal(0);
        for (OrderVO order : orders) {
            BigDecimal amount = order.getAmount();
            sum = sum.add(amount);
        }
        double v = sum.doubleValue();
        // 假设 OrderVO 有 getAmount 方法
        return v;
    }
}
